using IQIGame.Onigao.Framework;
using System.Collections.Generic;

namespace IQIGame.Onigao.Game
{
    public abstract class BaseCFSMState : IReusableClass
    {
        public int id { get; protected set; }
        public ConfigurableFSM fsm { get; protected set; }
        public bool active { get; internal set; }
        public uint MaxStore => 50;

        private Dictionary<int, object> _customParams;
        private List<CFSMCondition> _conditions = new List<CFSMCondition>();

        public void Init(ConfigurableFSM fsm, CFSMStateCfg stateCfg)
        {
            this.fsm = fsm;
            this.id = stateCfg.id;
            this._customParams = new Dictionary<int, object>();
            foreach (var param in stateCfg.customParams)
            {
                _customParams.Add(param.nameType, param.value);
            }
            foreach (int conditionId in stateCfg.conditions)
            {
                _conditions.Add(fsm.GetCondition(conditionId));
            }
            OnInit();
        }

        public void Update(float deltaTime)
        {
            OnUpdate(deltaTime);

            foreach (CFSMCondition condition in _conditions)
            {
                if (condition.Check())
                {
                    fsm.ChangeState(condition.nextStateId);
                    return;
                }
            }
        }

        public abstract void OnInit();

        public abstract void OnEnter(int prevStateId);

        public abstract void OnUpdate(float deltaTime);

        public abstract void OnExit();

        public virtual void OnReset()
        {
            _customParams = null;
            _conditions.Clear();
            id = 0;
            active = false;
            fsm = null;
        }
    }
}
